from django.views.generic import View
from django import http
from django_redis import get_redis_connection  # 获取redis的连接对象
import random, logging

from verifications.libs.captcha.captcha import captcha
from verifications.libs.constants import *
from urtils.response_code import RETCODE
from celery_tasks.sms.tasks import send_sms_code


# 创建日志输出文件
logger = logging.getLogger("django")


class ImageCodeView(View):
    # 图形验证码
    def get(self, request, uuid):
        #return http.HttpResponse('xxx')

        # 实现主体业务逻辑：生成，保存，响应图形验证码
        # 生成图形验证码
        text, image = captcha.generate_captcha()
        # return http.HttpResponse('xxx')
        # 保存图形验证码
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex(uuid, IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图形验证码
        return http.HttpResponse(image, content_type='image/png')


class SMSCodeView(View):
    # 短信验证码
    def get(self, request, mobile):
        """
        :param mobile: 手机号
        :return:　json
        """
        # 接受参数
        image_code_client = request.GET.get("image_code")
        uuid = request.GET.get("uuid")
        # 检验参数
        if not all([image_code_client, uuid]):
            return http.HttpResponseForbidden("缺少必传参数")

        # 获取链接到数据库
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get(mobile)
        if send_flag:
            return http.JsonResponse({"code": RETCODE.THROTTLINGERR, "errmsg": "发送短信过于频繁"})
        # 提取图片验证码
        image_code_server = redis_conn.get(uuid)
        if image_code_server is None:
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "图形验证码已失效"})
        # 删除图形验证码
        redis_conn.delete(uuid)
        # 对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_server.lower() != image_code_server.lower():
            return http.JsonResponse({"code": RETCODE.IMAGECODEERR, "errmsg": "输入验证码有误"})

        # 生成手机验证码: 随机６位数字
        sms_code = "%06d" % random.randint(0,999999)
        logger.info(sms_code)  # 手动输出日志，记录手机验证码
        # 创建pipeline管道
        pl = redis_conn.pipeline()
        # 保存手机验证码
        pl.setex(mobile,SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送短信验证码的标记
        pl.setex("send_sms%s" %mobile,SEND_SMS_CODE_INTERVAL, 1)
        # 执行
        pl.execute()
        # 发送手机验证码
        # CPP().send_templates_msm(mobile,[sms_code, SMS_CODE_REDIS_EXPIRES // 60], SEND_SMS_TEMPLATE_ID)

        # 使用celery发送短信验证码  触发任务
        send_sms_code.delay(mobile, sms_code)  # delay: 翻译　延迟

        # 响应结果
        return http.JsonResponse({"code": RETCODE.OK, "errmsg": "OK"})